// mircoApp/activityClock/comm/timeSelectPop/timeSelectPop.js
const skinBehavior = require("../../../../utils/themeSkin/skinBehavior");
Component({
  behaviors: [skinBehavior],
  /**
   * 组件的属性列表
   */
  options: {
    multipleSlots: true,	// 启用支持多个插槽
    addGlobalClass: true,
  },
  properties: {
    timeList:{
      type:Array,
      value:[]
    },
    coThemeColor:{
      type:String,
      default:'241, 83, 83'
    },
    iPnoneBottomBol:Boolean,
    timeIndex:Number,
    timeShow:Boolean
  },

  /**
   * 组件的初始数据
   */
  data: {
    dateShow:false,
    minDate: new Date(2000, 0, 1).getTime(),
    maxDate: new Date(2050, 10, 1).getTime(),
    currentDate: new Date().getTime(),
    endTime:'',
    startTime:'',
    timeType:'',
    startTimeName:'开始时间',
    endTimeName:'结束时间',
    timeName:'',
    result:[], //处理时间的结果
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    customTimeOn(event) {
      let {name} = event.currentTarget.dataset;
      this.setData({
        timeType:name,
        dateShow:true
      })
    },
    closeTime(event) {
      this.setData({
        timeShow:false
      })
    },
    //选择日期
    timeSelect(event) {
      let {item,index} = event.currentTarget.dataset;
      const today = new Date();
      const yesterday = new Date(today); //今天
      const dayOfWeek = today.getDay(); // 获取今天是星期几（0表示星期日，6表示星期六）
      let result = [];
      let yesterdayStart = '';
      let twoDaysAgoEnd = '';  
      // yesterday.setDate(today.getDate());  
      let yesterdayTime = new Date(today); //昨天
      const twoDaysAgo = new Date(today);  
      twoDaysAgo.setDate(today.getDate() - 2);  //最近三天
      yesterdayTime.setDate(today.getDate() - 1);
      if(item.value == 0) {
        this.setData({
          result:[]
        });
      } else if (item.value == 1) {
        yesterdayStart = this.getStartOfDayTimestamp(twoDaysAgo); 
        twoDaysAgoEnd = this.getEndOfDayTimestamp(yesterday); 
      } else if (item.value == 2) {
        yesterdayStart = this.getStartOfDayTimestamp(yesterday)
        twoDaysAgoEnd = this.getEndOfDayTimestamp(yesterday); 
      } else if (item.value == 3) {
        yesterdayStart = this.getStartOfDayTimestamp(yesterdayTime)
        twoDaysAgoEnd = this.getEndOfDayTimestamp(yesterdayTime);
      } else  if (item.value == 4) { 
        //  this.lastWeek();
        const dateRangeTimestamps = this.getTimestamps();
        yesterdayStart = dateRangeTimestamps.startOfPreviousWeek;
        twoDaysAgoEnd =  dateRangeTimestamps.endOfPreviousWeek;
      } else if (item.value == 5) {
        // 计算这一周的结束日期（星期日） 
        let startOfPreviousWeek = new Date(today);  
        startOfPreviousWeek.setDate(today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1)); 
        let endOfPreviousWeek = new Date(startOfPreviousWeek);  
        endOfPreviousWeek.setDate(startOfPreviousWeek.getDate() + 6);
        yesterdayStart = this.getStartOfDayTimestamp(startOfPreviousWeek)
        twoDaysAgoEnd = this.getEndOfDayTimestamp(endOfPreviousWeek); 
      } else if (item.value == 6) {
        //上一月的时间戳
        const dateTimestamps = this.getLastMonth();
        yesterdayStart = dateTimestamps.startOfPreviousMonth;
        twoDaysAgoEnd =  dateTimestamps.endOfPreviousMonth;
      }else if (item.value == 7) {
        //本月的时间戳
        const dateTimeMonth = this.getCurrentMonth();
        yesterdayStart = dateTimeMonth.startOfCurrentMonth;
        twoDaysAgoEnd =  dateTimeMonth.endOfCurrentMonth;
      } else {
        this.$toast('错误错误错误');
      }
      result.push(yesterdayStart);
      result.push(twoDaysAgoEnd);
      this.setData({
        result:result,
        timeName:item.name
      })
      this.triggerEvent('timeSelect', {item:item,index:index});
    },
    dateCancel() {
      if(this.data.timeType == 'start') {
        this.data.startTimeName ='开始时间';
        this.data.startTime = '';
      } else {
        this.data.endTimeName = '结束时间';
        this.data.endTime = '';
      }
      this.setData({
        dateShow:false,
        startTimeName:this.data.startTimeName,
        startTime:this.data.startTime,
        endTimeName:this.data.endTimeName,
        endTime:this.data.endTime
      })
    },
    dateConfirm(event) {
      if(this.data.timeType == 'start') {
        console.log(event);
        console.log(Date.parse(event.detail));
        this.data.startTimeName = this.timestampToTime(event.detail);
        this.data.startTime = event.detail;
      } else {
        this.data.endTimeName = this.timestampToTime(event.detail);
        this.data.endTime = event.detail;
      }
      this.setData({
        dateShow:false,
        result:[],
        timeName:'全部时间',
        startTimeName:this.data.startTimeName,
        startTime:this.data.startTime,
        endTimeName:this.data.endTimeName,
        endTime:this.data.endTime
      })
    },
    timeConfirm() {
      this.setData({
        timeShow:false
      })
      let result = [];
      result.push(this.data.startTime)
      result.push(this.data.endTime)
      if(this.data.result.length == 0) {
        this.setData({
          result:result
        })
      }
      this.triggerEvent('timeConfirm',{result:this.data.result,timeName:this.data.timeName});
    },
    getTimestamps() {  
        const now = new Date();  
        const dayOfWeek = now.getDay(); // 获取今天是星期几（0表示星期日，6表示星期六）  
        // 计算上一周的起始日期（星期一）的00:00:00  
        let startOfPreviousWeek = new Date(now);  
        startOfPreviousWeek.setDate(now.getDate() - dayOfWeek - (dayOfWeek === 0 ? 0 : 7) + 1);  
        startOfPreviousWeek.setHours(0, 0, 0, 0); // 设置时间为00:00:00  
      
        // 计算上一周的结束日期（星期日）的23:59:59  
        // 由于我们已经有了上一周的星期一，所以直接加6天即可得到上一周的星期日  
        let endOfPreviousWeek = new Date(startOfPreviousWeek);  
        endOfPreviousWeek.setDate(startOfPreviousWeek.getDate() + 6);  
        endOfPreviousWeek.setHours(23, 59, 59, 999); // 设置时间为23:59:59.999  
      
        // 验证结束日期确实在上一周（有时由于月份或年份变更，简单加6天可能不正确）  
        // 但在这个特定情况下，由于我们已经从星期一开始加6天到星期日，所以不需要额外验证  
      
        // 返回时间戳  
        return {  
            startOfPreviousWeek: startOfPreviousWeek.getTime(),  
            endOfPreviousWeek: endOfPreviousWeek.getTime()  
        };  
    },
    getLastMonth() {  
        const now = new Date();  
        const currentMonth = now.getMonth();  
        const currentYear = now.getFullYear();  
      
        // 计算上一个月  
        let previousMonth = currentMonth - 1;  
        let previousYear = currentYear;  
      
        // 处理上一个月是上一年的情况  
        if (previousMonth < 0) {  
            previousMonth = 11;  
            previousYear -= 1;  
        }  
        // 计算上一个月的第一天  
        let startOfPreviousMonth = new Date(previousYear, previousMonth, 1);  
        startOfPreviousMonth.setHours(0, 0, 0, 0); // 设置时间为00:00:00  
      
        // 计算上一个月有多少天  
        let daysInPreviousMonth = new Date(previousYear, previousMonth + 1, 0).getDate();  
      
        // 计算上一个月的最后一天  
        let endOfPreviousMonth = new Date(previousYear, previousMonth, daysInPreviousMonth);  
        endOfPreviousMonth.setHours(23, 59, 59, 999); // 设置时间为23:59:59.999  
      
        // 返回时间戳  
        return {  
            startOfPreviousMonth: startOfPreviousMonth.getTime(),  
            endOfPreviousMonth: endOfPreviousMonth.getTime()  
        };  
    },
    getCurrentMonth() {  
        const now = new Date();  
        const currentMonth = now.getMonth();  
        const currentYear = now.getFullYear();  
      
        // 计算本月的第一天  
        let startOfCurrentMonth = new Date(currentYear, currentMonth, 1);  
        startOfCurrentMonth.setHours(0, 0, 0, 0); // 设置时间为00:00:00  
      
        // 计算本月有多少天  
        let daysInCurrentMonth = new Date(currentYear, currentMonth + 1, 0).getDate();  
      
        // 计算本月的最后一天  
        let endOfCurrentMonth = new Date(currentYear, currentMonth, daysInCurrentMonth);  
        endOfCurrentMonth.setHours(23, 59, 59, 999); // 设置时间为23:59:59.999  
      
        // 返回时间戳  
        return {  
            startOfCurrentMonth: startOfCurrentMonth.getTime(),  
            endOfCurrentMonth: endOfCurrentMonth.getTime()  
        };  
    },
     // 辅助函数：获取指定日期的00:00:00时间戳  
      getStartOfDayTimestamp(date) {  
        const startOfDay = new Date(date);  
        startOfDay.setHours(0, 0, 0, 0);  
        return startOfDay.getTime();  
    },
    // 辅助函数：获取指定日期的23:59:59时间戳  
    getEndOfDayTimestamp(date) {  
        const endOfDay = new Date(date);  
        endOfDay.setHours(23, 59, 59, 999); // 毫秒设为999以确保是当天的最后一毫秒  
        return endOfDay.getTime();  
    },
    //日期转化
    timestampToTime(timestamp) {
      var date = new Date(timestamp);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10 ?
          "0" + (date.getMonth() + 1) :
          date.getMonth() + 1) + "-";
      let D = this.change(date.getDate()) + " ";
      return Y + M + D;
    },
    change(t) {
      if (t < 10) {
        return "0" + t;
      } else {
        return t;
      }
    },
  }
})